<%@ page language="java" import="java.util.*" pageEncoding="utf8"%>
<!Doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


    <%
        String path = request.getContextPath();
        String rootPath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + "/";
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
        request.setAttribute("basePath", basePath);
        request.setAttribute("rootPath", rootPath);
        pageContext.setAttribute("newLineChar", "\n");
    %>

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

    <title>日志监控任务</title>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>plugin/datatables/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>plugin/datatables/dataTables.bootstrap.css  "/>
    <script src="<%=basePath%>plugin/datatables/jquery.js"></script>
    <script src="<%=basePath%>plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="<%=basePath%>plugin/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
    <script src="<%=basePath%>plugin/datatables/bootstrap.min.js"></script>
    <script src="<%=basePath%>plugin/date/bootstrap-datetimepicker.min.js"></script>
    <script src="<%=basePath%>plugin/handlebars-v3.0.1.js"></script>
</head>


<body>
<div class="container">
    <button type="button" class="btn btn-default btn-sm" data-toggle="modal" data-target="#myModal">添加任务</button>
    <table id="example" class="table table-striped table-bordered">
        <thead>
        <tr>
            <th>序号</th>
            <th>任务名</th>
            <th>ConfCode</th>
            <th>任务组</th>
            <th>查询条件</th>
            <th>状态</th>
            <th>cron表达式</th>
            <th>描述</th>
            <th>操作</th>
        </tr>
        </thead>
    </table>
</div>
<!-- Button trigger modal -->


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">新增</h4>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    <div class="form-group">
                        <input type="hidden" class="form-control" id="jobId" name="jobId" />
                        <input type="text" class="form-control" id="jobName" name="jobName" placeholder="任务名">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="confCode" name="confCode" placeholder="ConfCode">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control"  id="jobGroup" name="jobGroup" placeholder="任务组">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="queryKey" name="queryKey" placeholder="查询条件"/>
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="cronExpression" name="cronExpression" placeholder="cron表达式"/>
                    </div>
                    <div class="form-group">
                        <textarea class="form-control" id="description" name="description" placeholder="任务描述" ></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="statusModalLabel">启动状态更改</h4>
            </div>
            <div class="modal-body">
                <div class="btn-group">
                    <select class="form-control" id="job_status">
                        <option value="start">开启</option>
                        <option value="stop">关闭</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="job_status_save">保存</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
<!--定义操作列按钮模板-->
<!--说下这里使用模板的作用，除了显示和数据分离好维护以外，绑定事件和传值也比较方便，希望大家能不拼接html则不拼接-->
<script id="tpl" type="text/x-handlebars-template">
    {{#each func}}
    <button type="button" class="btn btn-{{this.type}} btn-sm" onclick="{{this.fn}}">{{this.name}}</button>
    {{/each}}
</script>

<script>
    var basePath = '<%=basePath%>';
    var table;
    var editFlag = false;
    $(function () {

        $('#start_date').datetimepicker();

        var tpl = $("#tpl").html();
        //预编译模板
        var template = Handlebars.compile(tpl);

        table = $('#example').DataTable({
            "searching" : false,
            "paging": false,
            ajax: {
                url: basePath+ "task/list.htm"
            },
            "order": [[1, 'asc']],// dt默认是第一列升序排列 这里第一列为序号列，所以设置为不排序，并把默认的排序列设置到后面
            "serverSide": true,
            "columns": [
                {"data": "jobId"}, //因为要加行号，所以要多一列，不然会把第一列覆盖
                {"data": "jobName"},
                {"data": "confCode"},
                {"data": "jobGroup"},
                {"data": "queryKey"},
                {"data": function(source){
                    return source.jobStatus == '1' ? "<label class='btn-success'>已开启</label>" : "<label class='btn-danger'>已关闭</label>";
                }},
                {"data": "cronExpression"},
                {"data": "description"},
                {"data": null}
            ],
            "columnDefs": [
                {
                    "searchable": false,
                    "orderable": false,
                    "targets": [0.-1]
                },
                {
                    "targets": 8,
                    "render": function (a, b, obj, d) {
                        var context =
                        {
                            func: [
                                //{"name": "修改", "fn": "edit(\'" + c.name + "\',\'" + c.position + "\',\'" + c.salary + "\',\'" + c.start_date + "\',\'" + c.office + "\',\'" + c.extn + "\')", "type": "primary"},
                                {"name": "启动状态", "fn": "showStatus(\'" + obj.jobId + "\', \'" + obj.jobName + "\', \'" + obj.jobStatus + "\')", "type": "danger"},
                                {"name": "更改计划", "fn": "showEdit(\'" + obj.jobId + "\', \'" + obj.jobName + "\',\'" + obj.cronExpression + "\',\'" + obj.queryKey + "\')", "type": "warning"}
                            ]
                        };
                        var html = template(context);
                        return html;
                    }
                }

            ],
            "language": {
                "lengthMenu": "每页_MENU_ 条记录",
                "zeroRecords": "没有找到记录",
                "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
                "infoEmpty": "无记录",
                "search": "搜索：",
                "infoFiltered": "(从 _MAX_ 条记录过滤)",
                "paginate": {
                    "previous": "上一页",
                    "next": "下一页"
                }
            },
            "dom": "<'row'<'col-xs-2'l><'#mytool.col-xs-4'><'col-xs-6'f>r>" +
            "t" +
            "<'row'<'col-xs-6'i><'col-xs-6'p>>",
            "initComplete": function () {
                $("#mytool").append('');
            }

        });

        //添加序号
        //不管是排序，还是分页，还是搜索最后都会重画，这里监听draw事件即可
        /*        table.on('draw.dt',function() {
         table.column(0, {
         search: 'applied',
         order: 'applied'
         }).nodes().each(function(cell, i) {
         //i 从0开始，所以这里先加1
         i = i+1;
         //服务器模式下获取分页信息
         var page = table.page.info();
         //当前第几页，从0开始
         var pageno = page.page;
         //每页数据
         var length = page.length;
         //行号等于 页数*每页数据长度+行号
         //                        var columnIndex = (i+pageno*length);
         //                        cell.innerHTML = columnIndex;
         });
         }).draw();*/

        $("#save").click(save);
        $("#job_status_save").click(updateStatusAjax);

    });

    /**
     * 清除
     */
    function clear() {
        $("#jobName").val("").attr('disabled',false);
        $("#jobGroup").val("").attr('disabled',false).show();
        $("#description").val("").attr('disabled',false).show();
        $("#confCode").val("").attr('disabled',false).show();
        $("#queryKey").val("");
        $("#cronExpression").val("");
        // 清除job status
        $('#job_status').removeAttr('job_id');
        $('#job_status').val("");
    }

    /**
     * 判断字符串是否不为空
     */
    function strIsNotEmpty(v){
        return v !== null && v !== undefined && v !== '';
    }

    /**
     * 保存或修改
     */
    function save(){
        var jobId = $('#jobId').val();
        console.log('jobId =' + jobId);
        var url = ""
        if(strIsNotEmpty(jobId)){
            url =basePath+"task/updateCron.htm";
        }else{
            url =basePath+"task/add.htm";
        }
        ajax(url);
    }

    /**
     * ajax方法
     *
     * */
    function ajax(url) {
        $.ajax({
            type : "POST",
            async : false,
            dataType : "JSON",
            cache : false,
            url : url,
            data : $("#addForm").serialize(),//对表单进行序列化
            success : function(data) {
                if (data.flag) {
                    table.ajax.reload();
                    $("#myModal").modal("hide");
                    $("#myModalLabel").text("新增");
                    clear();
                    console.log("结果" + data);
                } else {
                    alert(data.msg);
                }
            }//end-callback
        });//end-ajax
    }

    /**
     *查看启动状态
     */
    function showStatus(id,jobName, state){
        console.log("id = " + id +"  state = " + state);
        $('#statusModalLabel').text('任务['+jobName+"]启动状态更改");
        $('#job_status').attr('job_id',id);
        if(state == '1'){
            $('#job_status').val('start');
        }else{
            $('#job_status').val('stop');
        }
        $("#statusModal").modal("show");
    }

    /**
     * 修改job状态
     */
    function updateStatusAjax() {
        console.log("updateStatusAjax click ----- ");
        var url =basePath +"/task/changeJobStatus.htm";
        $.ajax({
            url:url ,
            data: {
                "jobId": $('#job_status').attr('job_id'),
                "cmd": $('#job_status').val()
            }, success: function (data) {
                table.ajax.reload();
                $("#statusModal").modal("hide");
                clear();
                console.log("结果" + data);
            }
        });
    }


    /**
     *编辑方法
     **/
    function showEdit(jobId, jobName, cronExpression,queryKey) {
        $("#myModalLabel").text("修改corn计划");
        $("#jobId").val(jobId);
        $("#jobName").val(jobName).attr('disabled',true);
        $("#confCode").attr('disabled',true).hide();
        $("#jobGroup").attr('disabled',true).hide();
        $("#description").attr('disabled',true).hide();
        $("#cronExpression").val(cronExpression);
        $("#queryKey").val(queryKey);
        $("#myModal").modal("show");
    }

    function writeObj(obj){
        var description = "";
        for(var i in obj){
            var property=obj[i];
            description+=i+" = "+property+"\n";
        }
        return description;
    }




    /**
     * 删除数据
     * @param name
     */
    function del(name) {
        $.ajax({
            url: "/del.jsp",
            data: {
                "name": name
            }, success: function (data) {
                table.ajax.reload();
                console.log("删除成功" + data);
            }
        });
    }
</script>